package com.hfjava.practice04;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 * @version V1.0
 * @ProjectName:IntelliJ IDEA
 * @PackageName: com.hfjava.practice04
 * @ClassName: StaffTest
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @date 2019/12/24 19:55
 * @Copyright 大牛版板所有
 */
public class StaffTest {
    private static List<Staff> staffList = new ArrayList<>();

    public static void outputStaff(Object object){
        try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("chapter03\\doc\\staff.txt"))){
            oos.writeObject(object);
            oos.flush();
            System.out.println("写入信息成功！");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void inputStaff(){
        try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream("chapter03\\doc\\staff.txt"))){
            ArrayList<Staff> staffList = (ArrayList<Staff>)ois.readObject();
            for (Staff staff:staffList) {
                System.out.println(staff.getName()+"\t"+staff.getAge()+"岁，\t"+staff.getSalary());
            }
            System.out.println("读出信息成功！");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void saveStaffToFile(Staff staff, File file){
        ArrayList<Staff> staff1 = null;
        // 先读出
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))){
            staff1 = (ArrayList<Staff>)ois.readObject();
            staff1.add(staff);
        }catch (Exception e1){
            e1.printStackTrace();
        }

        // 再写入
        try (ObjectOutputStream oos1 = new ObjectOutputStream(new FileOutputStream(file))){
            oos1.writeObject(staff1);
            oos1.flush();
            System.out.println("增加信息成功！");
        }catch (Exception e2){
            e2.printStackTrace();
        }
    }

    public static void readStaffFromFile(File file){
        try (ObjectInputStream ois1 = new ObjectInputStream(new FileInputStream(file))){
            ArrayList<Staff> staffList1 = (ArrayList<Staff>)ois1.readObject();
            for (Staff sta:staffList1) {
                System.out.println(sta.getName()+"\\"+sta.getAge()+"\\"+sta.getSalary());
            }
            System.out.println("读出对象成功");
        }catch (Exception e){
            e.printStackTrace();
        }
        //return null;
    }

    public static void main(String[] args) {
        staffList.add(new Staff("Rose",23,4000));
        staffList.add(new Staff("Kate",25,4500));
        outputStaff(staffList);
        inputStaff();

        Staff staff = new Staff("Tom", 30, 5000);
        File file = new File("chapter03\\doc\\staff.txt");
        saveStaffToFile(staff,file);


       File file1 = new File("chapter03\\doc\\staff.txt");
       readStaffFromFile(file1);
    }
}
